import { useState, useEffect, useContext } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { AppContext } from '../../store'
import { getLocale } from '../../i18n'
import { dataManager } from '../../utils/dataManager'
import { ArtifactBase } from '../../types/artifact'
import ModelViewer from '../../components/ModelViewer'
import './detail.scss'

function ArtifactDetail() {
  const { state } = useContext(AppContext)
  const i18n = getLocale(state.locale)
  const [artifact, setArtifact] = useState<ArtifactBase | null>(null)
  const [currentTab, setCurrentTab] = useState<'story' | 'material' | 'archaeological'>('story')
  const [selectedLight, setSelectedLight] = useState<string>('')

  useEffect(() => {
    // 获取路由参数
    const instance = Taro.getCurrentInstance()
    const id = instance.router?.params.id
    
    if (id) {
      loadArtifact(id)
    } else {
      Taro.showToast({
        title: i18n.common.error,
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  }, [])

  const loadArtifact = (id: string) => {
    const data = dataManager.getArtifactById(id)
    if (data) {
      setArtifact(data)
      if (data.lightConfigs.length > 0) {
        setSelectedLight(data.lightConfigs[0].id)
      }
      // 设置导航栏标题
      Taro.setNavigationBarTitle({
        title: data.getName(state.locale)
      })
    } else {
      Taro.showToast({
        title: i18n.common.error,
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  }

  const handleChatClick = () => {
    if (!artifact) return
    Taro.navigateTo({
      url: `/pages/artifact/chat?id=${artifact.id}`
    })
  }

  if (!artifact) {
    return (
      <View className='artifact-detail-container'>
        <View className='loading-wrapper'>
          <Text className='loading-text'>{i18n.common.loading}</Text>
        </View>
      </View>
    )
  }

  return (
    <View className='artifact-detail-container'>
      <ScrollView 
        scrollY 
        className='detail-scroll'
        enableBackToTop
      >
        {/* 3D展示区域 */}
        <View className='model-viewer'>
          <ModelViewer
            modelConfig={artifact.modelConfig}
            lightConfigs={artifact.lightConfigs}
            selectedLightId={selectedLight}
          />

          {/* 光照切换 */}
          <View className='lighting-controls'>
            <Text className='lighting-title'>{i18n.artifact.lighting}</Text>
            <ScrollView scrollX className='lighting-scroll'>
              <View className='lighting-list'>
                {artifact.lightConfigs.map((light) => (
                  <View
                    key={light.id}
                    className={`lighting-item ${selectedLight === light.id ? 'active' : ''}`}
                    onClick={() => setSelectedLight(light.id)}
                  >
                    <View 
                      className='lighting-dot'
                      style={{ backgroundColor: light.color }}
                    />
                    <Text className='lighting-name'>
                      {state.locale === 'zh' ? light.name : light.nameEn}
                    </Text>
                  </View>
                ))}
              </View>
            </ScrollView>
          </View>
        </View>

        {/* 基本信息 */}
        <View className='artifact-info'>
          <View className='info-header'>
            <Text className='info-title'>{artifact.getName(state.locale)}</Text>
            <View className='info-meta'>
              <View className='meta-item'>
                <Text className='meta-label'>{i18n.artifact.dynasty}：</Text>
                <Text className='meta-value'>
                  {state.locale === 'zh' ? artifact.dynasty : artifact.dynastyEn}
                </Text>
              </View>
              <View className='meta-item'>
                <Text className='meta-label'>{i18n.artifact.period}：</Text>
                <Text className='meta-value'>
                  {state.locale === 'zh' ? artifact.period : artifact.periodEn}
                </Text>
              </View>
            </View>
          </View>

          {/* 标签页 */}
          <View className='info-tabs'>
            <View 
              className={`tab-item ${currentTab === 'story' ? 'active' : ''}`}
              onClick={() => setCurrentTab('story')}
            >
              <Text className='tab-text'>{i18n.artifact.story}</Text>
            </View>
            <View 
              className={`tab-item ${currentTab === 'material' ? 'active' : ''}`}
              onClick={() => setCurrentTab('material')}
            >
              <Text className='tab-text'>{i18n.artifact.material}</Text>
            </View>
            <View 
              className={`tab-item ${currentTab === 'archaeological' ? 'active' : ''}`}
              onClick={() => setCurrentTab('archaeological')}
            >
              <Text className='tab-text'>{i18n.artifact.archaeological}</Text>
            </View>
          </View>

          {/* 内容区域 */}
          <View className='info-content'>
            {currentTab === 'story' && (
              <View className='content-story'>
                <Text className='story-text'>{artifact.getStory(state.locale)}</Text>
              </View>
            )}

            {currentTab === 'material' && (
              <View className='content-materials'>
                {artifact.materials.map((material) => (
                  <View key={material.id} className='material-item'>
                    <Text className='material-name'>
                      {state.locale === 'zh' ? material.name : material.nameEn}
                    </Text>
                    <Text className='material-description'>
                      {state.locale === 'zh' ? material.description : material.descriptionEn}
                    </Text>
                  </View>
                ))}
              </View>
            )}

            {currentTab === 'archaeological' && (
              <View className='content-layers'>
                {artifact.archaeologicalLayers.map((layer) => (
                  <View key={layer.id} className='layer-item'>
                    <View className='layer-header'>
                      <Text className='layer-name'>
                        {state.locale === 'zh' ? layer.name : layer.nameEn}
                      </Text>
                      <Text className='layer-depth'>
                        {i18n.artifact.depth}: {layer.depth}m
                      </Text>
                    </View>
                    <Text className='layer-period'>
                      {state.locale === 'zh' ? layer.period : layer.periodEn}
                    </Text>
                    <Text className='layer-description'>
                      {state.locale === 'zh' ? layer.description : layer.descriptionEn}
                    </Text>
                  </View>
                ))}
              </View>
            )}
          </View>
        </View>
      </ScrollView>

      {/* 悬浮按钮 */}
      <View className='float-button' onClick={handleChatClick}>
        <Text className='float-button-icon'>💬</Text>
        <Text className='float-button-text'>{i18n.artifact.chatWithMe}</Text>
      </View>
    </View>
  )
}

export default ArtifactDetail

